var express = require("express");
var router = express.Router();
const bcryptjs = require("bcryptjs");
const jwt = require("jsonwebtoken");
var { ArticleModel, commentModel, userModel } = require("../model/mtg");
var { courseModel } = require("../model/zw");

/* GET home page. */
router.get("/show", async function (req, res, next) {
  const artdata = await ArticleModel.find();
  res.send({ code: 200, msg: "200 akk", artdata });
});

// 关注/状态的修改-文章详情
router.post("/detstatus", async function (req, res, next) {
  const body = req.body;
  await ArticleModel.updateOne({ _id: body._id }, body);
  res.send({ code: 200, msg: "200 akk" });
});

// 数据根据ids进行数据的查找-测试款
router.get("/detids/:id", async function (req, res, next) {
  const ids = req.params.id;
  // console.log(ids);
  const list = await ArticleModel.findOne({ _id: ids });
  res.send({ code: 200, msg: "200 akk", list });
});

// 详情页评论
router.get("/comm", async (req, res) => {
  let comment = await commentModel.find().lean().populate("user");
  let comdata = [];
  let jsoncomment = {};
  comment.forEach((item) => {
    jsoncomment[item._id] = item;
  });

  comment.forEach((item) => {
    if (!item["com"]) {
      comdata.push(item);
    } else {
      if (!jsoncomment[item["com"]]["children"]) {
        jsoncomment[item["com"]]["children"] = [];
      }
      jsoncomment[item["com"]]["children"].push(item);
    }
  });
  res.send({ code: 200, comdata });
});

// 评论添加
router.post("/addcom", async function (req, res, next) {
  const body = req.body;
  await commentModel.create(body);
  res.send({ code: 200, msg: "200 akk" });
});

// 评论添加删除
router.get("/delcom", async function (req, res, next) {
  const id = req.query.id;
  // console.log(id);
  // await commentModel.deleteOne({_id:id})
  res.send({ code: 200, msg: "200 akk" });
});

// 文章及课程搜索
router.get("/searchcom", async function (req, res, next) {
  var articleAll = await ArticleModel.find();
  var courseAll = await courseModel.find();
  const search = req.query.search;
  const regkey = new RegExp(search);

  if (search) {
    articleAll = await ArticleModel.find({ title: regkey });
    courseAll = await courseModel.find({ title: regkey });
  } else {
    articleAll = [];
    courseAll = [];
  }
  res.send({ code: 200, msg: "200 akk", articleAll, courseAll });
});

// 登录注册及手机号
// 注册
router.post("/regs", async (req, res, next) => {
  const { username } = req.body;
  const user = await userModel.findOne({ username });
  if (user) {
    res.send({ code: 401, message: "账户已存在，请登录！" });
  } else {
    await userModel.create(req.body);
    console.log(req.body);
    res.send({ code: 200, message: "regs ok" });
  }
});

// 登录
const createToken = {
  getToken(jiamiData, expiresIn) {
    return jwt.sign({ data: jiamiData }, 'mtgceshi', { expiresIn: expiresIn });
  },
  verify(token) {
    try {
      return jwt.verify(token, 'mtgceshi');
    } catch (error) {
      return false;
    }
  },
};

router.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const user = await userModel.findOne({ username });
  if (user) {
    if (!bcryptjs.compareSync(password, user.password)) {
      res.json({ code: 402, message: "密码错误" });
    } else {
      // 用户验证通过，生成访问令牌和刷新令牌并返回给前端
      const accessToken=createToken.getToken('user', '3d');
      const refreshToken=createToken.getToken('user', '7d');
      res.json({
        code: 200,
        message: "登录成功",
        accessToken,
        refreshToken,
        user: user._id,
        nickname: user.nickname,
      });
    }
  } else {
    res.json({ code: 401, message: "账户不存在" });
  }
});

router.get("/tokencref", async (req, res) => {
  let authorization = req.headers.authorization;
  // console.log("后端进入添加接口,这是短token");
  if (authorization) {
    const token = authorization.split(" ")[1];
    if (createToken.verify(token)) {
      res.send({
        msg: "token有效",
        code: 200,
        data: "这是你应得的数据:D",
      });
    } else {
      res.send({
        msg: "token已经过期",
        code: 401,
      });
    }
  } else {
    res.send({
      msg: "无效的刷新令牌",
      code: 406,
    });
  }
});

router.post("/refresh", async (req, res) => {
  // console.log("进入令牌判断", req.body.RefreshToken);
  //判断传来的长token是否过期
  const token = req.body.RefreshToken;

  let accessToken = createToken.getToken("user", "7d");
  let refreshToken = createToken.getToken("user", "14d");
  // console.log("这是要传递的新token", accessToken);
  if (createToken.verify(token)) {
    //长token未失效走这里
    console.log("长token未失效");
    res.send({
      code: 200,
      msg: "长token未失效",
      accessToken: accessToken,
      refreshToken: refreshToken,
    });
  } else {
    console.log("refresh");
    // 长token失效走这里
    res.send({
      code: 401,
      msg: "刷新令牌已过期",
    });
  }
});

module.exports = router;
